package me.yidasanqian.crowdfunding.config;

import com.google.gson.Gson;
import me.yidasanqian.crowdfunding.service.IJwtService;
import me.yidasanqian.crowdfunding.util.JwtUtils;
import me.yidasanqian.crowdfunding.vo.ResultModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Linyu Chen
 */
@Configuration
public class ApiInterceptor extends HandlerInterceptorAdapter {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Resource
    private IJwtService jwtService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        String token = request.getHeader("token");
        log.debug("preHandle token <== " + token);
        Gson gson = new Gson();
        if (StringUtils.isEmpty(token)) {
            log.debug("您尚未登录");
            String json = gson.toJson(ResultModel.fail(1005, "您尚未登录"));
            response.getWriter().write(json);
            return false;
        }
        if(JwtUtils.parseJWT(token, "beihai") != null){
            log.debug("token合法");
            boolean isExist = jwtService.isExist(token);
            if (!isExist) {
                log.debug("token不存在您尚未登录");
                String json = gson.toJson(ResultModel.fail(1005, "您尚未登录"));
                response.getWriter().write(json);
                return false;
            } else {
                return true;
            }
        } else {
            log.debug("token不合法或者过期");
            String json = gson.toJson(ResultModel.fail(1004, "登录信息过时"));
            response.getWriter().write(json);
            return false;
        }
    }
}
